package servlet;

import bean.Result;
import biz.CartBiz;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "CreateCartServlet", value = "/CreateCartServlet.s")
public class CreateCartServlet extends HttpServlet {
    private CartBiz biz = new CartBiz();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Result result;
        HttpSession session = request.getSession();
        String uid = String.valueOf(session.getAttribute("userid")) ;
        System.out.println(uid);
        if(uid.equals("null") || uid.trim().isEmpty()){
            System.out.println(uid);
            result = new Result(0, "用户未登录", "login/Login-M.html");
        }else{
            try {


                String product = request.getParameter("product");
                String amount = request.getParameter("amount");
                if(!biz.queryProduct(uid, product, amount).equals(amount)){
                    biz.create(product, uid, amount);
                }
                result = new Result(1, "添加成功!", null);
            }catch (Exception e){
                e.printStackTrace();
                result = new Result(0, "添加失败!", null);
            }
        }

        String json = new Gson().toJson(result);
        response.getWriter().append(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
